<template>
	<div class="content-box">
		<TreeFilter
			title="部门列表"
			:data="treeDatas"
			id="deptId"
			label="deptName"
			children="children"
			:default-value="initParam.deptId"
			@change="changeTreeFilter"
		/>
		<div class="table-box" style="flex: 1; width: 0px">
			<ProTable
				ref="userTable"
				title="用户列表"
				row-key="userId"
				:columns="columns"
				:init-param="initParam"
				:request-api="getUserListApi"
				:request-auto="false"
			>
				<!-- 表格Header按钮 -->
				<template #tableHeader>
					<el-button type="primary" :icon="CirclePlus" @click="openUserDialog('新增', {})">新增用户</el-button>
				</template>
				<!-- 表格操作 -->
				<template #operation="scope">
					<!-- 超级管理员无操作 -->
					<template v-if="scope.row.userId != 1">
						<el-button type="primary" link :icon="View" @click="openUserDialog('查看', scope.row)">查看</el-button>
						<el-button type="primary" link :icon="EditPen" @click="openUserDialog('编辑', scope.row)">编辑</el-button>
						<el-button type="danger" link :icon="Delete" @click="deleteUser(scope.row)">删除</el-button>
					</template>
				</template>
			</ProTable>
		</div>
		<!-- 弹窗 -->
		<el-dialog v-model="userVisible" :title="userTitle" :destroy-on-close="true" width="30%" draggable>
			<el-form label-width="100px" ref="userFormRef" label-suffix=" :" :model="userFormModel" :disabled="userTitle == '查看'">
				<el-form-item label="归属部门">{{ userFormModel.dept_name }} </el-form-item>
				<el-form-item
					label="用户名称"
					prop="username"
					:rules="[
						{
							required: true,
							message: '请填写用户名称',
							trigger: 'blur'
						}
					]"
				>
					<el-input v-model="userFormModel.username" clearable placeholder="请填写用户名称"></el-input>
				</el-form-item>
				<el-form-item
					label="用户昵称"
					prop="nick_name"
					:rules="[
						{
							required: true,
							message: '请填写用户昵称',
							trigger: 'blur'
						}
					]"
				>
					<el-input v-model="userFormModel.nick_name" clearable placeholder="请填写用户昵称"></el-input>
				</el-form-item>
				<el-form-item
					label="密码"
					prop="password"
					:rules="[
						{
							required: true,
							message: '请填写密码',
							trigger: 'blur'
						}
					]"
					v-if="userTitle == '新增'"
				>
					<el-input v-model="userFormModel.password" clearable placeholder="请填写密码" type="password" show-password></el-input>
				</el-form-item>
				<el-form-item
					label="角色"
					prop="roleIds"
					:rules="[
						{
							required: true,
							message: '请选择角色',
							trigger: 'blur'
						}
					]"
				>
					<el-select v-model="userFormModel.roleIds" multiple style="width: 100%" placeholder="请选择角色">
						<el-option v-for="item in roleOptions" :key="item.role_id" :label="item.role_name" :value="item.role_id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="userFormModel.remark" placeholder="请填写备注" :rows="4" type="textarea"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="userVisible = false">{{ userTitle == "查看" ? "关闭" : "取消" }}</el-button>
					<el-button type="primary" @click="handleSubmit" v-if="userTitle != '查看'">确认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="tsx" setup name="userManage">
import TreeFilter from "@/components/TreeFilter/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Setting } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { getDeptListApi } from "@/api/modules/test/dept";
import { getUserListApi, addUserApi, deleteUserApi, updateUserApi } from "@/api/modules/test/user";
import { getRoleListApi } from "@/api/modules/test/role";
import { ElMessage, FormInstance } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";

const treeDatas = ref([]);
const userTable = ref();
const selectDeptId = ref("");
const selectDeptName = ref("");

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ deptId: "" });
// 获取部门
const getDeptDatas = async () => {
	const { result } = await getDeptListApi({});
	treeDatas.value = result as any;
	if (treeDatas.value.length) {
		initParam.deptId = (treeDatas.value[0] as any).deptId;
		// 弹窗赋值
		selectDeptId.value = (treeDatas.value[0] as any).deptId;
		selectDeptName.value = (treeDatas.value[0] as any).deptName;
	}
};

// 部门树切换
const changeTreeFilter = (val: string, labelName: string) => {
	initParam.deptId = val;
	// 切换时，赋值给弹窗
	selectDeptId.value = val;
	selectDeptName.value = labelName;
};

// 表单配置项
const columns: ColumnProps[] = [
	{
		type: "index",
		label: "序号",
		width: 150
	},
	{
		prop: "username",
		label: "用户名称",
		search: {
			el: "input"
		}
	},
	{
		prop: "nick_name",
		label: "昵称"
	},
	{
		prop: "dept_name",
		label: "部门"
	},
	// {
	// 	prop: "role_name",
	// 	label: "角色",
	// 	render: scope => {
	// 		const el = scope.row.roleObjs.map((item: any) => 
	// 			<el-tag style="margin-right: 10px;">{item.role_name}</el-tag>
	// 		)
	// 		// 渲染
	// 		return el;
	// 	}
	// },
	{
		prop: "operation",
		label: "操作",
		width: 350,
		fixed: "right"
	}
];

//
const userVisible = ref(false);
const userTitle = ref("");
const userFormRef = ref<FormInstance>();
const userFormModel = ref({
	userId: "",
	username: "",
	deptId: "",
	dept_name: "",
	nick_name: "",
	password: "",
	roleIds: [],
	remark: ""
});
const roleOptions = ref<any>([]);

const openUserDialog = async (title: string, row: any = {}) => {
	userVisible.value = true;
	userTitle.value = title;

	// 获取角色列表
	const { data } = await getRoleListApi({ pageNum: 1, pageSize: 9999 });
	roleOptions.value = (data as any).list;
	if (title == "新增") {
		userFormModel.value = { ...row, deptId: selectDeptId.value, dept_name: selectDeptName.value };
	} else {
		userFormModel.value = {...row, roleIds: row.roleObjs.map((item: any) => item.role_id)};

	}
};

// 提交
const handleSubmit = () => {
	userFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			if (userTitle.value === "新增") {
				const data = await addUserApi(userFormModel.value);
				ElMessage.success({ message: data.msg });
			} else {
				const data = await updateUserApi(userFormModel.value);
				ElMessage.success({message: data.msg})
			}
			userTable.value.getTableList();
			userVisible.value = false;
		} catch (err) {
			console.log(err);
		}
	});
};

// 删除用户
const deleteUser = async (val: any) => {
	await useHandleData(deleteUserApi, { userId: val.userId }, "删除用户");
	userTable.value.getTableList();
};
// 初始化请求
onMounted(async () => {
	await getDeptDatas();
});
</script>
<style lang="scss" scoped>
.content-box {
	display: flex;
	flex-direction: row;
	align-items: flex-start;

	.content-table {
		flex: 1;
		height: 100%;
	}
}
</style>